package com.simon.nearbyfootball.app.ui;

import java.util.List;
import java.util.Stack;

import com.simon.nearbyfootball.app.AppConfig;
import com.simon.nearbyfootball.app.AppConstant;
import com.simon.nearbyfootball.app.AppContext;
import com.simon.nearbyfootball.app.AppFactoryConfig;
import com.simon.nearbyfootball.app.R;
import com.simon.nearbyfootball.app.bean.City;
import com.simon.nearbyfootball.app.bean.CityList;
import com.simon.nearbyfootball.app.bean.LocationInfo;
import com.simon.nearbyfootball.misc.Logger;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

public class CityChangeActivity extends Activity{
	private eventReceiver mEventReceiver = new eventReceiver();
	private CityList m_all_city;
	private EditText m_search_view;
	private ScrollView m_scroll_main;
	private LinearLayout m_linear_main;
	private LinearLayout m_province_list;
	private RelativeLayout m_province_main;
	private View m_active_view;
	private Stack<chooseStage> m_stack_stage = new Stack<chooseStage>();
	private String backPageName = "返回";
	private String title = "选择城市";
	private View titleControllerView;
	private View titleLeftView;
	private ImageView titleLeftImageView;
	private TextView titleLeftTextView;
	private View titleRightView;
	private View titleSearchView;
	private TextView titleTextView;
	private boolean isLocated = false;
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onDestroy()
	 */
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		unregisterReceiver(mEventReceiver);
		super.onDestroy();
	}


	public class chooseStage {
		public String backString;
		public View effectiveView;
		public String titleString;

		protected chooseStage() {
		}
	}
	
	public class eventReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			Logger.funtcionEntry();
			CityChangeActivity.this.updateGpsCity(LocationInfo.getInstance().getCity());
			isLocated = true;
			Logger.funtcionExit();
		}
	}
	@Override
    public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		IntentFilter filter = new IntentFilter();
		filter.addAction(AppConstant.ACTION_LOCATION_UPDATE);
		registerReceiver(mEventReceiver, filter);

		m_all_city = CityList.getInstance(this);
		initView();
	}
	
	private void updateGpsCity(String city){
		TextView tv = (TextView) findViewById(R.id.tvGPSCityName);
		View itemView = findViewById(R.id.linearGpsCityItem);
		tv.setText(city);
		itemView.setTag(city);
		itemView.setOnClickListener(new View.OnClickListener(){
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String city = (String) v.getTag();
				CityChangeActivity.this.handleCitySelect(m_all_city.findCityByName(city));
			}
		});
		
		
	}
	
	
	public void onBackPressed(){
		if(m_stack_stage.size() == 0){
			if(!isLocated){
				Logger.debug("GPS location failed,use default city:" + AppFactoryConfig.getDefaultCity().toString());
				AppConfig.getInstance().setCity(AppFactoryConfig.getDefaultCity().getId());
				AppConfig.getInstance().save(AppContext.getAppContext());
			}
			gotoHomeScreen();
		}else{
			m_scroll_main.removeView(m_active_view);
			chooseStage localchooseStage = (chooseStage) m_stack_stage.pop();
			m_active_view = localchooseStage.effectiveView;
			m_scroll_main.addView(m_active_view);
			this.backPageName = localchooseStage.backString;
			this.title = localchooseStage.titleString;
			resetTitle(this.title, "返回");
			if(m_stack_stage.size() == 0){
				ViewUtility.unhideView(m_search_view);
			}
		}		
	}
	
	private void initHotCitiesView(){
		LinearLayout layoutHotCities = (LinearLayout)findViewById(R.id.linearHotCities);
		
		for(String hotCity:CityList.hotCities){
			View itemView = getLayoutInflater().inflate(R.layout.item_citychange, null);
			TextView textView = (TextView)itemView.findViewById(R.id.tvCateName);
			ImageView imageView = (ImageView)itemView.findViewById(R.id.ivChoose);
			imageView.setImageResource(R.drawable.gou);
			ViewUtility.hideView(imageView,false);
			textView.setText(hotCity);
			itemView.setTag(m_all_city.findCityByName(hotCity));
			itemView.setOnClickListener(new View.OnClickListener(){

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					handleCitySelect((City)v.getTag());
				}
				
			});
			
			layoutHotCities.addView(itemView);
		}
	}
	
	
	private void initCityListView(View v){
		RelativeLayout mainLayout = (RelativeLayout) getLayoutInflater().inflate(R.layout.citylist, null);
		LinearLayout cityListLayout = (LinearLayout) mainLayout.findViewById(R.id.llcitylist);
		City province = (City) v.getTag();
		
		for(City city:province.getCityList()){
			View itemView = getLayoutInflater().inflate(R.layout.item_citychange, null);
			TextView textView = (TextView)itemView.findViewById(R.id.tvCateName);
			textView.setText(city.getName());
			ImageView imageView = (ImageView) itemView.findViewById(R.id.ivChoose);
			ViewUtility.hideView(imageView, false);
			cityListLayout.addView(itemView);
			itemView.setTag(city);
			itemView.setOnClickListener(new View.OnClickListener(){

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					handleCitySelect((City)v.getTag());
				}
				
			});
		}
		m_scroll_main.addView(mainLayout);
		m_active_view = mainLayout;
	}
	
	
	private void initProvinceView(){
		List<City> provinceList = m_all_city.getProvinceList();
		m_province_main = (RelativeLayout) getLayoutInflater().inflate(R.layout.citylist, null);
		m_province_list = (LinearLayout) m_province_main.findViewById(R.id.llcitylist);
		
		for(City city:provinceList){
			View itemView = getLayoutInflater().inflate(R.layout.item_citychange, null);
			TextView textView = (TextView)itemView.findViewById(R.id.tvCateName);
			textView.setText(city.getName());
			m_province_list.addView(itemView);
			itemView.setTag(city);
			
			itemView.setOnClickListener(new View.OnClickListener(){

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					m_scroll_main.scrollTo(0, 0);
	                chooseStage localchooseStage = new chooseStage();
	                localchooseStage.effectiveView = m_active_view;
	                localchooseStage.titleString = title;
	                localchooseStage.backString = backPageName;
	                m_stack_stage.push(localchooseStage);
	                m_scroll_main.removeView(m_active_view);
	                title = "选择城市";
	                resetTitle(title,backPageName);
	                initCityListView(v);
				}
				
			});
		}
		m_scroll_main.addView(m_province_main);
		m_active_view = m_province_main;
	}
	
	private void initView(){
		setContentView(R.layout.citychange);
		initTitle();
		
		m_search_view = (EditText) findViewById(R.id.etSearchCity);
		m_scroll_main = (ScrollView) findViewById(R.id.llParentView);
		m_linear_main = (LinearLayout) findViewById(R.id.linearList);
		m_active_view = m_linear_main;
		
		TextView tv = (TextView) findViewById(R.id.tvGPSCityName);
		if(!LocationInfo.getInstance().isLocated()){
			tv.setText("定位中...");
		}else{
			updateGpsCity(LocationInfo.getInstance().getCity());
		}
		
		ImageView iV = (ImageView)findViewById(R.id.ivGPSChoose);
		ViewUtility.hideView(iV,false);
		
		initHotCitiesView();
		
		RelativeLayout otherCityLayout = (RelativeLayout)findViewById(R.id.linear2Other);
		
		otherCityLayout.setOnClickListener(new View.OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				ViewUtility.hideView(m_search_view,true);
                chooseStage localchooseStage = new chooseStage();
                localchooseStage.effectiveView = m_active_view;
                localchooseStage.titleString = title;
                localchooseStage.backString = backPageName;
                m_stack_stage.push(localchooseStage);
                m_scroll_main.scrollTo(0, 0);
                m_scroll_main.removeView(m_active_view);
                title = "选择省份";
                resetTitle(title,backPageName);
                
                initProvinceView();
			}
		});
		
		
		m_search_view.addTextChangedListener(new TextWatcher(){

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				String str = s.toString().trim();
				ViewGroup filtetedListView = (ViewGroup)m_scroll_main.findViewById(R.id.filteredList);
				View unfilteredListView = (View)m_scroll_main.findViewById(R.id.unfilteredList);
				filtetedListView.removeAllViews();
				LayoutInflater localLayoutInflater = LayoutInflater.from(CityChangeActivity.this);
				if(str.length() == 0){
					ViewUtility.hideView(filtetedListView,true);
					ViewUtility.unhideView(unfilteredListView);
				}else{
					List<City> searchCities = m_all_city.search(str);
					ViewUtility.hideView(unfilteredListView, true);
					ViewUtility.unhideView(filtetedListView);
					for(City city:searchCities){
						View itemView = localLayoutInflater.inflate(R.layout.item_citychange, null);
						TextView textView = (TextView)itemView.findViewById(R.id.tvCateName);
						textView.setText(city.getName());
						ImageView imageView = (ImageView) itemView.findViewById(R.id.ivChoose);
						itemView.setTag(city);
						ViewUtility.hideView(imageView,false);
						
						itemView.setOnClickListener(new View.OnClickListener(){

							@Override
							public void onClick(View v) {
								// TODO Auto-generated method stub
								City city = (City) v.getTag();
								handleCitySelect(city);
							}
							
						});
						
						filtetedListView.addView(itemView);
					}
				}
			}
			
		});
	}
	
	private void resetTitle(String titleText, String titleLeft) {
		titleTextView.setText(titleText);
		titleLeftTextView.setText(titleLeft);
	}
	
	protected void initTitle() {
		this.titleLeftView = findViewById(R.id.left_action);
		this.titleRightView = findViewById(R.id.right_action_parent);
		this.titleSearchView = findViewById(R.id.search_action);
		this.titleControllerView = findViewById(R.id.linearTitleControls);
		this.titleTextView = ((TextView) findViewById(R.id.tvTitle));
		this.titleLeftImageView = ((ImageView) findViewById(R.id.back_icon));
		this.titleLeftTextView = ((TextView) findViewById(R.id.left_btn_txt));
		setupDefaultTitle();
	}

	protected void setupDefaultTitle() {
		if (this.titleSearchView != null) {
			this.titleSearchView.setVisibility(8);
		}
		if (this.titleControllerView != null) {
			this.titleControllerView.setVisibility(8);
		}
		if (this.titleLeftImageView != null) {
			this.titleLeftImageView.setImageResource(R.drawable.bg_back);
		}
		if (this.titleRightView != null) {
			this.titleRightView.setVisibility(8);
		}
		if (this.titleLeftTextView != null) {
			this.titleLeftTextView.setText("返回");
		}
		if (this.titleLeftView != null) {
			this.titleLeftView.setOnClickListener(new View.OnClickListener() {
				public void onClick(View paramAnonymousView) {
					onBackPressed();
				}
			});
		}
		
		titleTextView.setText(title);
	}
	
	public void handleCitySelect(City city){
		Logger.debug("handleCitySelect:" + city.getName());
		AppConfig.getInstance().setCity(city.getId());
		gotoHomeScreen();
	}
	
	
	private void gotoHomeScreen(){
		Intent intent = new Intent(this, MainTabView.class);
        startActivity(intent);
        finish();
	}
	
	
	
}
